package org.springleaf.ui.token;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TokenHelper {
	
	public static final String TOKEN_NAME = "token_name";
	
	public static Log log = LogFactory.getLog("springleaf");

	public TokenHelper(){
	}
	
	/**
	 * 获得TokenName
	 */
	public String createTokenName(){
		return "tk_" + UUID.randomUUID().toString().substring(0,6);
	}
	
	/**
	 * 创建token(采用UUID)
	 */
	public String createToken(){
        return UUID.randomUUID().toString();
	}
	
	/**
	 * 将token设置到Session中
	 * @param request
	 * @param name
	 * @param token
	 */
	public void setToken(HttpServletRequest request,String name,String token){
		request.getSession().setAttribute(name, token);
	}
	
	/**
	 * 验证token是否匹配
	 */
	public boolean validate(HttpServletRequest request){
		String name = getTokenName(request);
		if(StringUtils.isNotBlank(name)){
			String token = getToken(request, name);
			if(StringUtils.isNotBlank(token)){
				String paramToken = request.getParameter(name);
				log.debug("name:" + name + ",token:" + paramToken + ",sessionToken:" + token);
				return token.equals(paramToken);
			}
		}
		return false;
	}
	
	/**
	 * 删除session中指定的token
	 * @param request
	 * @param name
	 */
	public void removeToken(HttpServletRequest request,String name){
		request.getSession().removeAttribute(name);
	}
	

	/**
	 * 得到session保存的token
	 * @param request
	 * @param tokenName
	 */
	public void removeToken(HttpServletRequest request) {
		String name = getTokenName(request);
		log.debug("remove token : name=" + name);
		if(name != null){
			removeToken(request, name);
		}
	}
	
	/**
	 * 得到token的名字
	 * @param request
	 */
	public String getTokenName(HttpServletRequest request){
		String name = request.getParameter(TOKEN_NAME);
		if(StringUtils.isBlank(name)){
			log.warn("tokenName is Blank");
		}
		return name;
	}
	
	/**
	 * 得到session保存的token
	 * @param request
	 * @param tokenName
	 */
	public String getToken(HttpServletRequest request,String tokenName){
		String token = (String) request.getSession().getAttribute(tokenName); 
		if(StringUtils.isBlank(token)){
			log.warn("token is Blank in session");
		}
		return token;
	}

	
}
